import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import {  Modal,Icon,Tabs,message,Table,Dropdown,Menu,Button,Input,Form ,Row,Col,Select,Switch,Popconfirm,Radio,DatePicker }from 'antd';
const Search = Input.Search;
const Option = Select.Option;
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import SearchPanel from '../common/SearchPanel';
import RemarkModal from '../common/RemarkModal';
import {
  ASSET_LEVEL,
  ACCOUNT_ROLE_TYPE
} from '../constants/index'
import api from '../api';
import moment from 'moment';
import {bind_change, bind_toggle} from '../common/State';
const {RangePicker} = DatePicker;


export default class WaitingInList extends React.Component {
    constructor(props, context){
        super(props, context);
        this.state={
           page:1,
           total:1,
           pageSize:10,
           list:[],
           search:{},
           searchFlag:true,
           visible:false,
           resetpwdId:null,
           session:{},
           remarkVisibility:false,
           submitPropertyVisility:false,
           selectedRowKeys:[],
           currentSelectedRecord:{},
           isBatch:false,
           keyword:"",
           // batchSubmitPropertyVisility:false,

        };
    }

    componentWillMount(){
      // let session = this.props.route.session;
      // this.setState({
      //   session,
      // })

      let {page,pageSize} = this.state
      this.doFetch(page,pageSize);
    }
     componentWillReceiveProps(nextProps){
        //  let session =  this.props.route.session;
        // this.setState({
        //   session
        // })
    }
    //查询列表
    async doFetch(page,size,searchCondition={}){

      this.setState({
        searchFlag:true
      })
      let session = this.props.route.session;
      let {keyword} = this.state;
      let result = {}
      if (session.role_type == "PLAN_ADMIN") {//计划管理人
        result = await api('/assets/asset/list',{pageNumber:page,pageSize:size,asset_status:"WAIT_TO_VERIFY",keyword:keyword,list_type:"NORMAL",...searchCondition});
      }else{
        result = await api('/assets/asset/list',{pageNumber:page,pageSize:size,asset_status:"WAIT_TO_APPLY",keyword:keyword,list_type:"NORMAL",...searchCondition});
      }

      if(result.success){
          this.setState({
            total:result.data.totalItem,
            list:result.data.pageResult||[],
            page,
            searchFlag:false,
            pageSize:result.data.pageSize,
            session,
          });
      }else{
        this.setState({
          searchFlag:false,
          session,

        })
        message.error(result.message)
      }

    }

    doSearch(){
      let {page,pageSize} = this.state;
      this.doFetch(page,pageSize);
    }









    onClickRemark(record){
      this.setState({
        currentSelectedRecord:record,
        remarkVisibility:true,
      })
    }


    onSearch(searchCondition){
      let {search} = this.state;
      search = {...searchCondition}
      this.setState({
        search,
        filterConditionVisibility:false,
      })

      this.doFetch(1,10,searchCondition)
    }

    onReset(){
      this.setState({
        search:{},
        filterConditionVisibility:false
      })
    }

    exportTable(e){
      if (e.key == "ALL") {
        
      }else if (e.key == "SELECTED") {
        
      }else{

      }
    }

    onSearchKeyWords(){

    }

    onSelectRows(selectedRowKeys, selectedRows){


       this.setState({
        selectedRowKeys,
        selectedRows,
       })
    }


    //点击提交资产按钮
    onClickSubmitProperty(record){
      this.setState({
        submitPropertyVisility:true,
        currentSelectedRecord:record,
        isBatch:false,
      })
    }

    async submitAssets(id){
      let asset_id_list = [id];
      let {session} = this.state;
      let assetStatusType = "";
      if (session.role_type == "ORIGINATOR") {//原始权益人
        assetStatusType = "WAIT_TO_VERIFY";
      }else{//计划管理人
        assetStatusType = "IN_POOL";
      }
      let result = await api('/assets/submit',{asset_id_list,assetStatusType});
      if (result.success) {
        message.success("提交成功");
        let {page,pageSize,list} = this.state;
        if (list.length == 1 && page > 1) {
          page = page - 1;
        }
        this.doFetch(page,pageSize);
      }else{
        message.error(result.message);
      }
      this.setState({
        searchFlag:false,
      })
    }

    //提交资产弹窗中的确定
    onSubmitPropertyConfirm(){
      let {currentSelectedRecord,isBatch} = this.state;
      this.setState({
        submitPropertyVisility:false,
        searchFlag:true
      })
      if (isBatch) {
        this.batchSubmitAssets();
      }else{
        this.submitAssets(currentSelectedRecord.id);
      }
                    
    }

    //提交备注说明
    onSubmitRemark(params){
      this.saveRemark(params)
    }

    async saveRemark(values) {
      let {currentSelectedRecord} = this.state;
      values.asset_id = currentSelectedRecord.id;
      let result = await api('/assets/remark/edit' ,values);
      if(!result.success){
        message.error(result.message);
        return
      }

      message.success('保存成功' , 1, () => {
        this.setState({remarkVisibility:false},() =>{
          this.doFetch()
        })
      })
    }

    //取消备注说明
    onCancelRemarkModal(){
      this.setState({
        remarkVisibility:false,
      })
    }

    //批量提交确定按钮
    clickBatchSubmitConfirm(){
      this.setState({
        submitPropertyVisility:true,
        isBatch:true,
      })
    }

    //批量提交
    async batchSubmitAssets(){
      let {selectedRows,session} = this.state;
      let asset_id_list = [];
      selectedRows.map((record,index) =>{
        asset_id_list.push(record.id);
      });
      let assetStatusType = "";

      if (session.role_type == "ORIGINATOR") {//原始权益人
        assetStatusType = "WAIT_TO_VERIFY";
      }else{//计划管理人
        assetStatusType = "IN_POOL";
      }
      let result = await api('/assets/submit',{asset_id_list,assetStatusType});
      if (result.success) {
        message.success("提交成功");
        let {page,pageSize,list} = this.state;
        if (list.length == selectedRows.length && page > 1) {
          page = page - 1;
        }
        this.doFetch(page,pageSize);
      }else{
        message.error(result.message);
      }
        this.setState({
          searchFlag:false,
          selectedRows:[],
          selectedRowKeys:[]
        })
    }

    //计划管理人退回资产
    async onClickSendBack(){
      this.setState({
        searchFlag:true,
      })
      let {currentSelectedRecord,session} = this.state;
      let asset_id_list = [currentSelectedRecord.id];
      let assetStatusType = "WAIT_TO_APPLY";
      let result = await api('/assets/submit',{asset_id_list,assetStatusType});
      if (result.success) {
        message.success("提交成功");
        let {page,pageSize,list} = this.state;
        if (list.length == 1 && page > 1) {
          page = page - 1;
        }
        this.doFetch(page,pageSize);
      }else{
        message.error(result.message);
      }
      this.setState({
        searchFlag:false,
        sendBackVisibility:false,
      })
    }

    
    //分页
    toPage({current:page,pageSize,total}){
      this.doFetch(page,pageSize);
    }

    changePageSizer(current,size){
      this.doFetch(current,size);
    }

    
    quickJumper(pageNumber,pageSize){
      this.doFetch(pageNumber,pageSize);
    }

    getExportMenu(){
      return (
          <Menu onClick={this.exportTable.bind(this)}>
            <Menu.Item key="ALL">导出全部</Menu.Item>
            <Menu.Item key="SELECTED">导出选中</Menu.Item>
          </Menu>
        )
    }

    getTableHeader(){
      let {selectedRowKeys,pageSize} = this.state;
      if (selectedRowKeys.length > 0 ) {
        return(
            <div className="table-header">
              <p className="table-header-content" > 
                已选中{selectedRowKeys.length}/{pageSize}
                <span className="marginR10 marginL10">|</span>
                <Button
                  type="primary"
                  size="small"
                  onClick={this.clickBatchSubmitConfirm.bind(this)}
                >提交入池</Button>
                <Button
                  type="primary"
                  className="marginL10"
                  size="small"
                >导出选中</Button>
               </p>
            </div>
          )
      }else{
        return(
            <div className="table-header">
              <span className="table-header-content">已选中0/{pageSize}</span>
            </div>
          )
      }
    }

    
    render() {

        var {list, page,total,searchFlag,departmentList,search,pageSize,selectedRowKeys,session}=this.state;
        return (
            <div >
                {/*<NavBar navs={[{title:'社区信息'}]} />*/}
                <ContentBody className='container'>
                  <div>
                      <div style={{"float":"left"}}>待入池资产</div>
                      <div>
                      <div className="text-right">
                        <Button
                          type="primary"
                          onClick={() => {
                            this.setState({
                              filterConditionVisibility:true,
                            })
                          }}
                          className="marginR10"
                          >筛选</Button>

                          <Dropdown 
                              overlay={this.getExportMenu()}
                              >
                            <Button
                              className='marginR10'
                            >导出<Icon type="down" /></Button>
                          </Dropdown>
                        

                        <Input
                            {...this::bind_change('keyword')}
                            placeholder="搜索关键字"
                            style={{"width":"120px"}}
                            className='marginR10'
                          />

                        <Button
                          type="primary"
                          icon="search"
                          onChange={this.onSearchKeyWords.bind(this)}
                        >搜索</Button>
                      </div>

                        
                      </div>
                  </div>

                  <Table
                    bordered
                    title={this.getTableHeader.bind(this)}
                    columns={this.getColumns()}
                    simple
                    dataSource={list}
                    pagination={{
                      current:page,
                      total:total,
                      pageSize:pageSize,

                    }}
                    loading={searchFlag}
                    onChange={this.toPage.bind(this)}
                    scroll={{ x: 1000 }}
                    rowKey={(record,index) => index}
                    rowSelection={{
                      onChange:this.onSelectRows.bind(this),
                      selectedRowKeys,
                    }}
                    className='marginT20'
                  />

                  <SearchPanel
                    visibility = {this.state.filterConditionVisibility}
                    onSearch = {this.onSearch.bind(this)}
                    onReset = {this.onReset.bind(this)}
                  />

                  {session.role_type == "ORIGINATOR" ?
                    <Modal
                      title="提示"
                      visible={this.state.submitPropertyVisility}
                      onOk={this.onSubmitPropertyConfirm.bind(this)}
                      onCancel={() => {
                        this.setState({
                          submitPropertyVisility:false,
                        })
                      }}
                    >
                      <p>确定要将选中的资产提交给计划管理人？</p>
                    </Modal>
                  :
                    <Modal
                      title="提示"
                      visible={this.state.submitPropertyVisility}
                      onOk={this.onSubmitPropertyConfirm.bind(this)}
                      onCancel={() => {
                        this.setState({
                          submitPropertyVisility:false,
                        })
                      }}
                    >
                      <p>确定要将选中的资产提交移入资产池？</p>
                    </Modal>
                  }

                  <Modal
                      title="提示"
                      visible={this.state.sendBackVisibility}
                      onOk={this.onClickSendBack.bind(this)}
                      onCancel={() => {
                        this.setState({
                          sendBackVisibility:false,
                        })
                      }}
                    >
                      <p>退回后无法选择该资产，确定要退回？</p>
                    </Modal>
                  

                  


                  <RemarkModal
                    visibility = {this.state.remarkVisibility}
                    onSubmitRemark = {this.onSubmitRemark.bind(this)}
                    onCancelRemarkModal = {this.onCancelRemarkModal.bind(this)}
                    userType={session.role_type}
                  >
                  </RemarkModal>

                </ContentBody>
            </div>
        );
    }

    getColumns(){
      let {session} = this.state;
      let columns = [
            {
              title: '编号',
              dataIndex: 'number',
              key: 'number',
            }, {
              title: '债务人',
              dataIndex: 'debtor',
              key: 'debtor',
            }, {
              title: '应收账款日',
              dataIndex: 'start_date',
              key: 'start_date',
            },{
              title: '分级',
              dataIndex: 'level',
              key: 'level',
              render:(level) =>{
                return ASSET_LEVEL[level];
              } 
            }, {
              title: '应收总金额',
              dataIndex: 'money_sum',
              key: 'money_sum',
            },{
              title: '当前余额',
              dataIndex: 'money_left',
              key: 'money_left'
            },{
              title: '预计收款日',
              dataIndex: 'predict_date',
              key: 'predict_date'
            },{
              title: '操作',
              key: 'action',
              fixed: 'right',
              width:160,
              render: (record) =>{
                if(!record.id) return;
                  return (
                        <span className={'table-operation'}>
                            <span>
                              <a
                                href='javascript:void 0'
                                onClick={() =>{
                                  this.context.router.push(`/underlyingAssets/propertyData/Detail?id=${record.id}`)
                                }}
                              >
                              查看
                              </a>
                              <i className='separator'>|</i>

                              <a 
                                href='javascript:void 0'
                                onClick={this.onClickSubmitProperty.bind(this,record)}
                                >
                                提交资产
                              </a>
                              <i className='separator'>|</i>
                              {session.role_type == "ORIGINATOR" ? 
                                <a
                                  href='javascript:void 0'
                                  onClick={this.onClickRemark.bind(this,record)}
                                >备注说明
                                </a>
                              :
                                <a
                                  href='javascript:void 0'
                                  onClick={() =>{
                                    this.setState({
                                      sendBackVisibility:true,
                                      currentSelectedRecord:record,
                                    })
                                  }}
                                >退回资产
                                </a>
                              }
                              
                            </span>
                        </span>
                      )
              } ,
            }
        ];

        return columns
    }
}
WaitingInList.contextTypes= { router: React.PropTypes.object.isRequired};
